package com.admin.kotlintest.activity.car

import android.app.Activity
import android.content.Intent
import cn.bmob.v3.BmobPushManager
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.PushListener
import cn.bmob.v3.listener.SaveListener
import com.admin.kotlintest.R
import com.admin.kotlintest.activity.MapActivity
import com.admin.kotlintest.base.BaseActivity
import com.admin.kotlintest.bean.Appointment
import com.admin.kotlintest.bean.Car
import com.admin.kotlintest.bean.Installation
import com.admin.kotlintest.bean.MyUser
import com.admin.kotlintest.dialog.DateTimeDialog
import com.admin.kotlintest.utils.DataUtil
import com.admin.kotlintest.utils.SystemUtils
import com.socks.library.KLog
import kotlinx.android.synthetic.main.activity_appiontment.*
import kotlinx.android.synthetic.main.layout_title.*
import org.jetbrains.anko.toast
import java.util.*

/**
 * Created by 吴昶 on 2018/4/18.
 */
class AppiontmentActivity:BaseActivity(),DateTimeDialog.MyOnDateSetListener{

    val chose_car=3
    val location=4
    var car: Car?=null
    var dialog:DateTimeDialog?=null
    var startTime:Long=0
    var endTime:Long=0
    var isStertTime:Boolean=true
    var fromLat:Double=0.0
    var fromLong:Double=0.0

    override fun onDateSet(date: Date?) {
        if(isStertTime){
            startTime=date!!.time
            if(endTime>0){
                if(startTime>=endTime){
                    startTime=0
                    toast("开始时间不能早于结束时间")
                }else{
                    tv_start_time.text=DataUtil.dateYMDHm.format(date)
                }
            }else{
                tv_start_time.text=DataUtil.dateYMDHm.format(date)
            }
        }else{
            endTime=date!!.time
            if(startTime>0){
                if(startTime>=endTime){
                    endTime=0
                    toast("结束时间不能早于开始时间")
                }else{
                    tv_end_time.text=DataUtil.dateYMDHm.format(date)
                }
            }else{
                tv_end_time.text=DataUtil.dateYMDHm.format(date)
            }
        }
    }

    override fun bindLayout(): Int {
        return R.layout.activity_appiontment
    }

    override fun initData() {
        tv_title.text="预约车辆"
    }

    override fun initEvent() {
        btn_apply_car.setOnClickListener {
            if(tv_car_number.text.toString()==""){
                toast("必须选择车辆")
                return@setOnClickListener
            }
            if(tv_start_time.text.toString()==""||tv_end_time.text.toString()==""){
                toast("请选择用车的起始时间")
                return@setOnClickListener
            }
            if(tv_from.text.toString()==""){
                toast("请选择出发地点")
                return@setOnClickListener
            }
            if(edt_remarks.text==null||edt_remarks.text.toString()==""){
                toast("请填写申请用途")
                return@setOnClickListener
            }

            var appointment=Appointment()
            appointment.carId=car!!.objectId
            appointment.carNumber=car!!.carNumber.toString()
            var user=BmobUser.getCurrentUser(MyUser::class.java)
            appointment.userId=user.objectId
            appointment.userName=user.username
            appointment.driverId=car!!.driver!!.objectId
            appointment.driverName=car!!.driver!!.username
            appointment.from=tv_from.text.toString()
            appointment.fromlat=fromLat
            appointment.fromlon=fromLong
            appointment.appointRemarks=edt_remarks.text.toString()
            appointment.appointStartTime=startTime
            appointment.appointEndTime=endTime
            appointment.appointState=0
            appointment.save(object:SaveListener<String?>(){
                override fun done(p0: String?, p1: BmobException?) {
                    p1?:let {
                        notification()
                    }
                    p1?.let {
                        toast("申请失败"+p1.message.toString())
                    }
                }
            })
        }

        tv_car_number.setOnClickListener {
            var intent=Intent(this,ChoseCarActivity::class.java)
            startActivityForResult(intent,chose_car)
        }

        tv_start_time.setOnClickListener {
            isStertTime=true
            if(dialog==null){
                dialog= DateTimeDialog(context,this)
            }
            dialog!!.show()
        }

        tv_end_time.setOnClickListener {
            isStertTime=false
            if(dialog==null){
                dialog= DateTimeDialog(context,this)
            }
            dialog!!.show()
        }

        tv_from.setOnClickListener {
            var intent=Intent(this,MapActivity::class.java)
            startActivityForResult(intent,location)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if(resultCode== Activity.RESULT_OK){
            if(requestCode==chose_car){
                car=data!!.getSerializableExtra("car") as Car
                tv_car_number.text=car!!.carNumber
                tv_car_driver.text=car!!.driver!!.username
            }else if(requestCode==location){
                tv_from.text=data!!.getStringExtra("address")
                fromLat=data.getDoubleExtra("lat",0.0)
                fromLong=data.getDoubleExtra("lon",0.0)
            }

        }
    }

    fun notification(){
        var manager=BmobPushManager<Installation>()
        var query=BmobQuery<Installation>()
        query.addWhereEqualTo("myUser",car!!.driver)
        var msg=SystemUtils.installationMsgFormat("新的用车申请","您有新的用车申请,请查收")
        manager.query=query
        manager.pushMessage(msg,object:PushListener(){
            override fun done(p0: BmobException?) {
                p0?:let { KLog.d("推送成功")
                    toast("申请成功，等待司机确认")}
                p0?.let { KLog.d("推送失败"+p0.message) }
                finish()
            }
        })
    }

}